let { skpm } = require('../package.json')
const HtmlWebpackPlugins = require('html-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')

const path = require('path')
const ROOT = path.resolve(__dirname, '../')
const DIST = path.resolve(ROOT, 'sketch-meaxure.sketchplugin/Contents/Resources')
const UI = path.resolve(ROOT, 'ui')
const DEMO = path.resolve(ROOT, 'demo')
const RESOURCES = path.resolve(ROOT, 'resources')

const devMode = process.env.NODE_ENV === 'development'

const webpackConfig = {
  mode: devMode ? 'development' : 'production',
  entry: {
    index: path.resolve(UI, 'index.ts')
  },
  output: {
    path: path.resolve(DIST),
    filename: devMode ? 'index.[hash].js' : 'index.js',
    publicPath: './'
  },
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        use: 'ts-loader',
        exclude: /node_modules/
      },
      {
        test: /\.(less|css)$/,
        use: [
          {
            loader: MiniCssExtractPlugin.loader,
            options: {
              hrm: devMode,
              reloadAll: devMode
            }
          },
          { loader: 'css-loader', options: { esModule: false, sourceMap: devMode } },
          'postcss-loader',
          { loader: 'less-loader', options: { sourceMap: devMode } }
        ]
      }
    ]
  },
  devServer: {
    contentBase: path.resolve(DEMO),
    publicPath: '/',
    compress: true,
    port: 8080,
    inline: true
  },
  resolve: {
    extensions: ['.tsx', '.ts', '.js']
  },
  plugins: [
    new HtmlWebpackPlugins({
      filename: 'template.html',
      template: path.resolve(UI, 'template.html'),
      devMode: devMode
    }),
    new MiniCssExtractPlugin({
      // 配置分离样式文件名，还有publicPath属性可根据需要进行配置
      filename: devMode ? 'index.[hash].css' : 'index.css'
    })
  ]
}

if (!devMode) {
  webpackConfig.plugins.push(
    new CopyWebpackPlugin([
      {
        // resources\
        from: path.resolve(RESOURCES, 'panel/assets/js/jquery-2.2.4.min.js'),
        to: 'jquery.js'
      }
    ])
  )
  webpackConfig.plugins.push(new CleanWebpackPlugin())
}

module.exports = webpackConfig
